<template>
  <div id="postAddPage">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <!-- 帖子标题 -->
        <van-field
            v-model="addPostData.title"
            name="title"
            label="帖子标题"
            placeholder="请输入标题"
            :rules="[{ required: true, message: '请输入标题' }]"
        />

        <!-- 帖子内容 -->
        <van-field
            v-model="addPostData.content"
            rows="6"
            autosize
            label="帖子内容"
            type="textarea"
            placeholder="请输入帖子内容"
            :rules="[{ required: true, message: '请输入帖子内容' }]"
        />

        <!-- 图片上传 -->
        <van-field name="uploader" label="选择图片（非必须，最多四张）">
          <template #input>
            <van-uploader
                v-model="fileList"
                :after-read="onFileChange"
                :max-count="4"
                multiple
                accept="image/*"
                @delete="deleteImage"
            />
          </template>
        </van-field>
      </van-cell-group>

      <!-- 提交按钮 -->
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          确定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { Toast, ImagePreview } from 'vant';
import { useRouter } from 'vue-router';
import myAxios from "../../plugins/myAxios.ts";

const router = useRouter();

// 表单数据
const addPostData = ref({
  title: '', // 帖子标题
  content: '', // 帖子内容
});

// 文件列表
const fileList = ref([]);

// 文件上传处理
const onFileChange = (file) => {
  if (file.status === 'failed') {
    Toast('文件上传失败，请重试');
  } else if (file.status === 'done') {
    Toast('文件上传成功');
  }
};

// 表单提交
const onSubmit = async () => {
  // 构造表单数据
  const formData = new FormData();
  formData.append('title', addPostData.value.title);
  formData.append('content', addPostData.value.content);

  // 如果有图片，则添加到表单数据
  if (fileList.value.length > 0) {
    fileList.value.forEach((file, index) => {
      formData.append(`file${index + 1}`, file.file);
    });
  }

  // 发送请求
  try {
    const res = await myAxios.post('/post/add', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });

    if (res?.code === 0 && res.data) {
      Toast.success('发布成功');
      router.push({ path: '/post', replace: true });
    } else {
      Toast.fail(res?.message || '发布失败');
    }
  } catch (error) {
    Toast.fail('请求失败，请稍后重试');
    console.error('提交失败：', error);
  }
};

// 图片预览（点击放大）
const previewImage = (index) => {
  const images = fileList.value.map((file) => file.content);
  ImagePreview({ images, startPosition: index });
};

// 删除已上传的图片
/*const deleteImage = (file, { index }) => {
  fileList.value.splice(index, 1);
  Toast('图片已删除');
};*/
</script>

<style scoped>
#postAddPage {
  padding: 16px;
}
</style>
